package com.turtle.learning.auth.controller;

import com.turtle.learning.auth.dto.LoginDTO;
import com.turtle.learning.auth.dto.LoginUserInfo;
import com.turtle.learning.auth.dto.RegisterUserDTO;
import com.turtle.learning.auth.service.LoginService;
import com.turtle.learning.auth.utils.SecurityUtil;
import com.turtle.learning.auth.utils.TokenOperator;
import com.turtle.learning.users.entity.User;
import com.turtle.learning.users.service.impl.UserServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 认证授权控制器
 *
 * @author turtle
 * @since: 2020-05-05
 */

@RestController
@Api(tags = "认证授权模块")
@RequestMapping("/auth")
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class AuthController {

    private final TokenOperator tokenOperator;
    private final UserServiceImpl userService;
    private final LoginService loginService;


    /**
     * 登录
     *
     * @param loginDTO 登录信息
     * @return token 生成的凭证
     */
    @PostMapping("login")
    @ApiOperation(value = "登录")
    public String login(@Validated @RequestBody LoginDTO loginDTO) {
        String token = loginService.login(loginDTO.getUsername(), loginDTO.getPassword());
        return token;
    }

    /**
     * 获取认证授权的用户信息
     *
     * @return Claims
     */
    @ApiOperation(value = "获取认证授权的用户信息")
    @GetMapping("user/info")
    public LoginUserInfo getLoginUserInfo() {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        return tokenOperator.getUserInfo(((ServletRequestAttributes) attributes).getRequest());
    }

    /**
     * 用户注册
     *
     * @param registerUser 注册用户信息
     * @return Boolean 注册是否成功
     */
    @ApiOperation(value = "用户注册")
    @PostMapping("register")
    public Boolean registerUser(@Validated @RequestBody RegisterUserDTO registerUser) {

        User user = User.builder()
            .roles("user")
            .username(registerUser.getUsername())
            .password(SecurityUtil.encryptPassword(registerUser.getPassword()))
            .build();
        return userService.save(user);

    }
}
